package com.gmrz.uap.policy;

import com.gmrz.uap.authmetadata.AuthMetadataService;
import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ConditionConst;
import com.gmrz.uap.common.ControllerSupport;
import com.gmrz.uap.dict.DictConst;
import com.gmrz.uap.dict.DictService;
import com.gmrz.uap.model.AuthMetadata;
import com.gmrz.uap.model.Policy;
import com.gmrz.uap.model.UasConfig;
import com.gmrz.uap.operlog.OperLogService;
import com.gmrz.uap.resource.ResourceInterceptor;
import com.gmrz.uap.uasconfig.UasConfigService;
import com.gmrz.uap.util.Identities;
import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.List;

public class PolicyController extends ControllerSupport {
    private static final Logger LOG = LogManager.getLogger(PolicyController.class);

    /**
     * 元数据主页面
     */
    @Before(ResourceInterceptor.class)
    public void index() {

        /*String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);


        List<AuthMetadata> all = AuthMetadataService.me.findAll();
        setAttr("aaids", all);
        setAttr("dataType", SystemConst.getDbType());
        setAttr("maxPolicyValue", UasConfigService.me.getMaxPolicyValue() - 1);*/
    }


    public void getPolicyListByTenantId() {
        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);
        List<Policy> policies = PolicyService.me.findAll(tenantId);
        convertPolicyName(policies);
        render(responseJsonRender(policies.toArray()));
    }


    private void convertPolicyName(List<Policy> policies) {
        if (!policies.isEmpty()) {
            for (Policy policy : policies) {
                convertPolicyName(policy);
            }
        }
    }


    private void convertPolicyName(Policy policy) {
        StringBuilder sb = new StringBuilder();

        sb.append(SystemConst.POLICY_NAME).append("_").append(policy.getTenantId());

        if (StringUtils.isNotBlank(policy.getAuthType())) {//拼接验证类型
            sb.append("_").append(SystemConst.getAuthType(policy.getAuthType()));
        }

        if (StringUtils.isNotBlank(policy.getTransType())) {//拼接交易类型
            sb.append("_").append(SystemConst.getTransType(policy.getTransType()));
        }

        policy.setPolicyName(sb.toString());
    }

    /**
     * 返回策略详细
     */
    public void getPolicyAaid() {

        String plid = getPara("plid");

        String tenantid = getCookie(SystemConst.COOKIE_TENANT_ID);

        List<AuthMetadata> policyAaid = PolicyService.me.getPolicyAaid(plid, tenantid);

        render(responseJsonRender(policyAaid.toArray()));
    }

    /**
     * 返回所有策略
     */
    public void getAllAaid() {

        String plid = getPara("plid");
        String tenantid = getCookie(SystemConst.COOKIE_TENANT_ID);

        List<AuthMetadata> policyAaid = PolicyService.me.getPolicyAaid(plid, tenantid);

        List<AuthMetadata> allAaid = AuthMetadataService.me.findAll();

        allAaid.removeAll(policyAaid);

        render(responseJsonRender(allAaid.toArray()));
    }

    /**
     * 删除策略
     */
    public void remove() {

        Policy policy = getModel(Policy.class);

        try {
            policy = Policy.dao.selectPolicyByPolicyId(policy.getPlId());
            flag = PolicyService.me.removePolicy(policy, getCookie(SystemConst.COOKIE_TENANT_ID));

            if (flag) {
                message = getRes().get("policy.form.remove.success");
                String cacheKey = ConditionConst.UAF_POLICY_CONFIG_KEY + getCookie(SystemConst.COOKIE_TENANT_ID)+"."
                        +policy.getAuthType()+"."+policy.getTransType()+".";

                List<Record> list = Policy.dao.selectPolicyConfigNameByPolicyId(policy.getPlId());
                if (list != null && list.size() > 0){
                    for(Record r : list){
                        // 删除策略参数
                        Policy.dao.deletePolicyConfigById(r.getStr("policy_config_id"));
                        // 拼接缓存key
                        String key = cacheKey + r.getStr("config_name");
                        // 删除此策略下策略参数的缓存
                        message = AmmsCacheUtil.deleteIfSuccess(key, message);
                    }
                }
                // 策略缓存删除
                message = AmmsCacheUtil.deleteIfSuccess(AmmsCacheUtil.POLICYJSON, message);
            } else {
                message = getRes().get("policy.form.remove.failure");
            }

        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }


        //增加系统操作日志
        OperLogService.me.addOperLog("删除策略", policy.getPlId(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 增加页面跳转
     */
    public void add() {
        setAttr("authTypeList", DictService.me.getDictListByDictTypeID(DictConst.DICT_TYPE_STATICS_AUTH_AUTH_TYPE_ID));
        setAttr("transTypeList", DictService.me.getDictListByDictTypeID(DictConst.DICT_TYPE_TRANS_TYPE_ID));
        render("form" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 保存策略名
     */
    public void save() {

        Policy model = getModel(Policy.class);

        String policyName = "POLICY_" + getCookie(SystemConst.COOKIE_TENANT_ID) + "_" + model.getAuthType() + "_" + model.getTransType();

        String cacheKey = ConditionConst.UAF_POLICY_CONFIG_KEY  + getCookie(SystemConst.COOKIE_TENANT_ID) + "." + model.getAuthType() + "." + model.getTransType() + ".";

        //判断策略名称是否存在
        boolean existFlag = PolicyService.me.exist(policyName);
        if (existFlag) {
            result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
            result.put(SystemConst.RESPONSE_RESULT_MESSAGE, "该策略已存在，请勿重复添加");
            render(responseJsonRender(result));
            return;
        }

        try {
            String policyId = Identities.uuid2();
            model.setPlId(policyId);
            flag = PolicyService.me.savePolicy(model, getCookie(SystemConst.COOKIE_TENANT_ID));

            if (flag) {
                message = getRes().get("policy.form.add.success");
                // 查询uas_config中webauth的相关数据
                List<UasConfig> ucList = UasConfigService.me.getConfigListByType(3);
                if (ucList != null && ucList.size() > 0){
                    for(UasConfig uc : ucList){
                        // 将查询出的webauth相关数据与当前新增的策略id绑定存入策略参数表中
                        Policy.dao.policyConfigSave(policyId,
                                uc.getConfigEname(), uc.getConfigValue(), "webauth", uc.getDataType());

                        // 拼接缓存key
                        String key = cacheKey + uc.getConfigEname();
                        // 删除策略参数的缓存，新增策略时默认的将缓存中与webauth的一些策略参数数据删除
                        message = AmmsCacheUtil.deleteIfSuccess(key, message);
                    }
                }
                // 删除策略的缓存
                message = AmmsCacheUtil.deleteIfSuccess(AmmsCacheUtil.POLICYJSON, message);
            } else {
                message = "策略信息添加失败，请稍后重试！";
            }

        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }

        //增加系统操作日志
        OperLogService.me.addOperLog("增加策略", model.getPolicyName(), flag, message, getRequest());

        convertPolicyName(model);

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        result.put(SystemConst.RESPONSE_RESULT_DATA, model);
        render(responseJsonRender(result));
    }

    /**
     * 保存策略详情
     */
    public void savePolicyAuth() {

        String ids = getPara("ids");
        String plid = getPara("plid");
        String texts = getPara("texts");
        String pl_name = getPara("pl_name");

        String[] arr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);


        flag = PolicyService.me.savepolicyAuth(plid, arr, getCookie(SystemConst.COOKIE_TENANT_ID));

        if (flag) {
            message = getRes().get("policy.form.refresh.success");

            try {
                message = AmmsCacheUtil.deleteIfSuccess(AmmsCacheUtil.POLICYJSON, message);
            } catch (JedisConnectionException jedisConnectionException) {
                message += getRes().get("redis.connection.failed");
                LOG.error(message, jedisConnectionException);
            }
        } else {
            message = getRes().get("policy.form.refresh.failure");
        }


        //增加系统操作日志
        OperLogService.me.addOperLog2("更新策略详情", pl_name, ids, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    public void verifyPolicyNmu() {

        String ids = getPara("ids");
        String plid = getPara("plid");

        String[] arr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);

        int maxPolicyValue = UasConfigService.me.getMaxPolicyValue();

        if (arr.length > maxPolicyValue) {

            result.put("flag", flag);
            result.put("msg", getRes().get("policy.form.refresh.limit"));
        } else {
            flag = true;
            result.put("flag", flag);
        }

        render(responseJsonRender(result));
    }


    public void removeByPolicyIdAndMetadataId() {
        String ids = getPara("ids");
        String plid = getPara("plid");
        String texts = getPara("texts");
        String pl_name = getPara("pl_name");

        String tenantId = getCookie(SystemConst.COOKIE_TENANT_ID);

        flag = PolicyService.me.removeByPolicyIdAndMetadataId(plid, ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA), tenantId);

        //增加系统操作日志
        OperLogService.me.addOperLog2("更新策略详情", pl_name, ids, flag, message, getRequest());

        if (flag) {
            message = "移除已接受元数据信息成功";

            try {
                message = AmmsCacheUtil.deleteIfSuccess(AmmsCacheUtil.POLICYJSON, message);
            } catch (JedisConnectionException jedisConnectionException) {
                message += getRes().get("redis.connection.failed");
                LOG.error(message, jedisConnectionException);
            }
        } else {
            message = "移除已接受元数据信息失败，请稍后重试！";
        }

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);

        render(responseJsonRender(result));

    }




    /**
     * 策略参数管理页面
     */
    public void policyConfigManager() {
        Policy policy = getModel(Policy.class);
        setAttr("policyId", policy.getPlId());
        render("configManager" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 策略参数列表
     */
    public void policyConfigList(){
        String policyId = getPara("policyId");

        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, "equ_model");
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        Page<Record> descPage = PolicyService.me.policyConfigListByPolicyId(page, rows, sort, order, policyId);
        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        setAttr("policyId", policyId);
        render(responseJsonRender(result));
    }

    /**
     *  跳转策略参数新增页面
     */
    public void policyConfigAdd() {
        String policyId = getPara("policyId");
        setAttr("policyId", policyId);
        render("policyConfigForm" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     *  策略参数新增保存
     */
    public void policyConfigSave() {
        String policyId = getPara("policyId");
        String policyConfigName = getPara("policyConfigName");
        String policyConfigValue = getPara("policyConfigValue");
        String policyConfigDes = getPara("policyConfigDes");
        Policy.dao.policyConfigSave(policyId, policyConfigName, policyConfigValue, policyConfigDes, "string");
        message = "添加成功";
        // 删除缓存
        //message = AmmsCacheUtil.deleteIfSuccess("uaf.cache.equipment.forbid.version." + equipment.getEquModel(), message);
        flag = true;
        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 跳转策略参数编辑页面
     */
    public void policyConfigEdit() {
        String policyConfigId = getPara();

        Record record = Policy.dao.getByPolicyConfigId(policyConfigId);

        setAttr("policyConfigName", record.getStr("config_name"));
        setAttr("policyConfigValue", record.getStr("config_value"));
        setAttr("policyConfigDes", record.getStr("des"));
        setAttr("policyConfigId", policyConfigId);
        setAttr("policyConfigDataType", record.getStr("data_type"));
        render("policyConfigForm" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 策略参数更新
     */
    public void policyConfigUpdate(){
        String policyConfigId = getPara("policyConfigId");
        //String policyConfigName = getPara("policyConfigName");
        String policyConfigValue = getPara("policyConfigValue");
        String policyConfigDes = getPara("policyConfigDes");

        Policy.dao.policyConfigUpdate(policyConfigId, policyConfigValue, policyConfigDes);
        message = "编辑成功";

        Record policyConfigRecord = Policy.dao.getByPolicyConfigId(policyConfigId);
        String policyConfigName = policyConfigRecord.getStr("config_name");
        // 根据策略参数id查询策略的认证方式、业务场景
        Record record = Policy.dao.getAuthTypeTransTypeByPolicyConfigId(policyConfigId);
        // 拼接缓存key
        String key = ConditionConst.UAF_POLICY_CONFIG_KEY + getCookie(SystemConst.COOKIE_TENANT_ID)+"."
                +record.getStr("auth_type")+"."+record.getStr("trans_type")+"."+policyConfigName;
        // 删除策略参数缓存
        message = AmmsCacheUtil.deleteIfSuccess(key, message);
        flag = true;
        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     *  删除策略参数
     */
    public void policyConfigRemove(){
        String policyConfigId = getPara("policyConfigId");
        String policyConfigName = getPara("policyConfigName");
        String[] idArr = policyConfigId.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
        String[] nameArr = policyConfigName.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
        // 根据策略参数id查询策略的认证方式、业务场景
        Record record = Policy.dao.getAuthTypeTransTypeByPolicyConfigId(idArr[0]);
        for (String id : idArr) {
            Policy.dao.deletePolicyConfigById(id);
        }
        message = "删除成功";
        for(String name : nameArr){
            // 拼接缓存key
            String key = ConditionConst.UAF_POLICY_CONFIG_KEY + getCookie(SystemConst.COOKIE_TENANT_ID)+"."
                    +record.getStr("auth_type")+"."+record.getStr("trans_type")+"." + name;
            // 删除策略参数缓存
            message = AmmsCacheUtil.deleteIfSuccess(key, message);
        }
        flag = true;
        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


}
